package com.xinghai.web.controller.api;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinghai.common.core.controller.BaseController;
import com.xinghai.common.core.domain.AjaxResult;
import com.xinghai.common.utils.DataUtil;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.SecurityUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.common.utils.bean.BeanUtils;
import com.xinghai.system.domain.*;
import com.xinghai.system.domain.entity.DataUpdateDTO;
import com.xinghai.system.domain.entity.UpdateInfoDTO;
import com.xinghai.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.rmi.ServerException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * api接口
 *
 * @author xinghai
 * @date 2024-12-04
 */
@RestController
@RequestMapping("/api")
public class QdApiController extends BaseController
{
    @Autowired
    private IQdUserService userService;
    @Autowired
    private IQdUserWalletLogService walletLogService;
    @Autowired
    private IQdUserWalletService walletService;
    @Autowired
    private IQdPayService payService;
    @Autowired
    private IQdPayOrderInfoService orderInfoService;
    @Autowired
    private IQdStoreService storeService;


    /**
     * 查询用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo()
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        return success(user);
    }

    /**
     * 查询首页通知
     */
    @GetMapping("/getNotice")
    public AjaxResult getNotice()
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        if (StringUtils.isNotBlank(user.getUserNotice())){
            return success((Object) user.getUserNotice());
        }
        //展示店铺消息
        QdStore store =storeService.getById(user.getAscriptionStore());
        if (store!=null&&StringUtils.isNotBlank(store.getStoreNotice())){
            return success((Object) store.getStoreNotice());
        }
        return success((Object) "欢迎使用本系统！！！");
    }


    /**
     * 获取我的数据
     */
    @GetMapping("/getMyData")
    public AjaxResult getMyData()
    {
        Map<String,Object> map = new HashMap<>();
//        QdUserWallet wallet = null;
//        try {
//            wallet = userWalletService.checkWallet(StpUtil.getLoginId(""));
//        } catch (ServerException e) {
//            return error("获取信息失败");
//        }

        QdUser user = userService.getByLoginId(StpUtil.getLoginId(""));
        QdUserWalletLog qdUserWalletLog = new QdUserWalletLog();
        qdUserWalletLog.setType("1");
        qdUserWalletLog.setUserId(StpUtil.getLoginId(0L));
        //插入时间查询
        qdUserWalletLog.setParams(DataUtil.getCreateTimeParams());
        BigDecimal todayMoney = walletLogService.sumMoney(qdUserWalletLog);
        QdPayOrderInfo qdPayOrder = new QdPayOrderInfo();
        qdPayOrder.setUserId(user.getId());
        qdPayOrder.setParams(DataUtil.getCreateTimeParams());
        QueryWrapper<QdPayOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        queryWrapper.between("create_time", qdPayOrder.getParams().get("beginCreateTime"),qdPayOrder.getParams().get("endCreateTime"));
        List<QdPayOrderInfo> qdPayOrderInfo = orderInfoService.list(queryWrapper);
        BigDecimal todayBuyAmount = qdPayOrderInfo.stream().map(QdPayOrderInfo::getBuyAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal todaySellAmount = qdPayOrderInfo.stream().map(QdPayOrderInfo::getSellAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal todayDiff = qdPayOrderInfo.stream().map(QdPayOrderInfo::getDiff).reduce(BigDecimal.ZERO, BigDecimal::add);
        int todayBuyNum = qdPayOrderInfo.stream().map(QdPayOrderInfo::getBuyNum).reduce(0, Integer::sum);
        int todaySellNum = qdPayOrderInfo.stream().map(QdPayOrderInfo::getSellNum).reduce(0, Integer::sum);
        map.put("todayMoney",todayMoney);//今日佣金
//        map.put("amount",wallet.getWithdrawalWallet());//佣金余额
//        map.put("allAmount",wallet.getAllWallet());//累计佣金
        map.put("todayBuyAmount",todayBuyAmount);//今日买入金额
        map.put("todayBuyNum",todayBuyNum);//今日买入数量
        map.put("todaySellAmount",todaySellAmount);//今日卖出金额
        map.put("todaySellNum",todaySellNum);//今日卖出金额
        map.put("todayDiff",todayDiff);//今日收益
        map.put("pushNum",user.getPushNum());//直推人数
        map.put("teamNum",user.getTeamNum());//团队人数
//        map.put("achievement",wallet.getAchievement());//我的业绩
        return success(map);
    }


    /**
     * 修改用户信息
     */
    @PostMapping("/updateInfo")
    public AjaxResult updateInfo(@Validated @RequestBody UpdateInfoDTO updateInfoDTO)
    {
        if (StringUtils.isNotBlank(updateInfoDTO.getPassword())){
            if (updateInfoDTO.getPassword().length()<6||updateInfoDTO.getPassword().length()>20){
                return error("密码设置不符合规范");
            }
            updateInfoDTO.setPassword(SecurityUtils.encryptPassword(updateInfoDTO.getPassword()));
        }else {
            updateInfoDTO.setPassword(null);
        }
        QdUser user = new QdUser();
        //组装参数
        BeanUtils.copyBeanProp(user,updateInfoDTO);
        user.setId(StpUtil.getLoginId(0L));
        return success(userService.updateById(user));
    }


    /**
     * 我的团队数据
     */
    @PostMapping("/myTeamData")
    public AjaxResult myTeamData(@RequestBody DataUpdateDTO dto)
    {
        String userId = dto.getUserId();
        if (StringUtils.isBlank(userId)){
            userId = StpUtil.getLoginId("");
        }
        QdUser user = userService.getByLoginId(userId);
        String s = userService.queryAllChild(userId);
        Map<String,Object> map = new HashMap<>();
//        QdPay pay = new QdPay();
//        //插入时间查询
//        pay.setParams(DataUtil.getCreateTimeParams());
//        pay.setUserIdsSeller(StpUtil.getLoginId(""));
//        List<QdPay> list = payService.list(pay);
//        //我的业绩
//        BigDecimal myMoney = list.stream().filter(m -> m.getBuyerUserId().equals(user.getId())).map(QdPay::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
//        QdUser param = new QdUser();
//        param.setSuperId(user.getId());
//        //查询直推数据
//        List<QdUser> list1 = userService.list(param);
//        List<Long> collect = list1.stream().map(QdUser::getId).collect(Collectors.toList());
//        //直推业绩
//        BigDecimal pushMoney = list.stream().filter(m -> collect.stream().anyMatch(qdUserId -> qdUserId.equals(m.getBuyerUserId()))).map(QdPay::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
//        //团队业绩
//        BigDecimal teamMoney = list.stream().map(QdPay::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

//        QdUserWallet wallet = new QdUserWallet();
//        wallet.setParams(DataUtil.getCreateTimeParams());
//        wallet.setUserIds(s);
//        List<QdUserWallet> list = walletService.list(wallet);
//        map.put("myMoney",list.stream().filter(qdUserWallet -> qdUserWallet.getUserId().equals(user.getId())).map(QdUserWallet::getNowMoney).reduce(BigDecimal.ZERO, BigDecimal::add));
        QdUserWallet wallet = new QdUserWallet();
        //插入时间查询
        //wallet.setParams(DataUtil.getCreateTimeParams());
        wallet.setUserIds(s);
        List<QdUserWallet> list = walletService.list(wallet);
        //我的业绩
        BigDecimal myMoney = list.isEmpty()?BigDecimal.ZERO:list.stream().filter(qdUserWallet -> qdUserWallet.getUserId().equals(user.getId())).map(QdUserWallet::getNowMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        QdUser param = new QdUser();
        param.setSuperId(user.getId());
        //查询直推数据
        List<QdUser> list1 = userService.list(param);
        List<Long> collect = list1.stream().map(QdUser::getId).collect(Collectors.toList());
        //直推业绩
        BigDecimal pushMoney = list.stream().filter(qdUserWallet -> collect.stream().anyMatch(qdUserId -> qdUserId.equals(qdUserWallet.getUserId()))).map(QdUserWallet::getNowMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        //团队业绩
        BigDecimal teamMoney = list.stream().map(QdUserWallet::getNowMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        map.put("myMoney",myMoney);//我的业绩
        map.put("pushMoney",pushMoney);//直推业绩
        map.put("teamMoney",teamMoney);//团队业绩
        map.put("teamNum",user.getTeamNum());//团队人数
        map.put("pushNum",user.getPushNum());//直推人数
        return success(map);
    }

    /**
     * 我的团队数据
     */
    @PostMapping("/myTeamList")
    public AjaxResult myTeamList(@RequestBody DataUpdateDTO dto)
    {
        String userId = dto.getUserId();
        if (StringUtils.isBlank(userId)){
            userId = StpUtil.getLoginId("");
        }
        QdUser user = new QdUser();
        user.setSuperId(Long.valueOf(userId));
        List<QdUser> list = userService.list(user);
        List<Map<String,Object>> mapList = list.stream().map(m->{
            Map<String,Object> map = new HashMap<>();
            map.put("userId",m.getId());//用户id
            map.put("avatar",m.getAvatar());//头像
            map.put("userPhone",m.getUserPhone());//手机号
            map.put("nickName",m.getNickName());//昵称
            QdPay pay = new QdPay();
            //插入时间查询
            pay.setParams(DataUtil.getCreateTimeParams());
            pay.setBuyerUserId(m.getId());
//            List<QdPay> payList = payService.list(pay);
//            map.put("achievement",payList.stream().map(QdPay::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));//我的业绩
            QdUserWallet wallet = walletService.getByUserId(String.valueOf(m.getId()));
            map.put("achievement",wallet.getNowMoney());//我的业绩
            map.put("teamNum",m.getTeamNum());//团队人数
            map.put("pushNum",m.getPushNum());//直推人数
            map.put("joinTime",DateUtils.dateTimeByDate(m.getCreateTime()));//加入时间
            return map;
        }).collect(Collectors.toList());
        return success(mapList);
    }

}
